package demo3;

public class Text01 {
    public static void main(String[] args) throws InterruptedException {
        // 初始化累加对象
        Counter01 counter = new Counter01();
        // 创建两个线程对一个变量进时累加
        // 线程1
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });
        // 线程2
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase1();
            }
        });

        // 启动线程
        t1.start();
        t2.start();

        // 等待线程完成
        t1.join();
        t2.join();

        // 查看运行结果
        System.out.println("count = " + counter.count);
    }
}

// 专门用来累加的类
class Counter01 {
    // 初始值是0
    public int count = 0;
    /**
     * 累加方法
     */

    public synchronized void increase () {
        count++;
    }

    public void increase1 () {
        count++;
    }
}